
export default class PermissionUtils {
    private static instance: PermissionUtils;

    public static getInstance() {
        if (!this.instance) {
            this.instance = new PermissionUtils();
        }
        return this.instance;
    }


    private constructor() {

    }
    /**
     * 判断是否有权限
     * @param list 权限数组
     * 
     * @returns \{state: 是否全部有权限, list: 没有权限组成的数组}
     */
    public has<T extends ApiPermissions>(list: T[]) {
        const resultList = api.hasPermission({
            list
        });
        const granteds = resultList.filter((item) => {
            return !item.granted;
        });
        return {
            state: granteds.length === 0,
            list: granteds.map((item) => { return item.name }) as T[]
        }

    }

    /**
     * 请求权限
     * @param list 权限数组
     * 
     * @returns \{state: 是否全部有权限, list: 没有权限组成的数组}
     */
    public request<T extends ApiPermissions>(list: T[]) {
        return new Promise<{ state: boolean, list: T[] }>((resolve) => {
            api.requestPermission({
                list
            }, (ret) => {
                const resultList = ret.list;
                const granteds = resultList.filter((item) => {
                    return !item.granted;
                });
                resolve({
                    state: granteds.length === 0,
                    list: granteds.map((item) => { return item.name }) as T[]
                });
            });
        });
    }
}
